<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/22
 * Time: 14:09
 */
namespace App\Http\Model\Mysql;

use Illuminate\Database\Eloquent\Model;

class CategoryModel extends Model
{
    const IS_DELETE     =   1,
          NOT_DELETE    =   0;

    const IS_SHELF      =   1,
          NOT_SHELF     =   0;

    protected $table    =   'mini_category';

    protected $dateFormat   =   'U';

    protected $guarded  =   [];

    /**
     * 搜索有效分类
     * @param $query
     */
    public function scopeActive($query)
    {
        $query->where(['is_shelf' => self::IS_SHELF, 'is_delete' => self::NOT_DELETE]);
    }

    /**
     * 生成无限极递归树
     * @param array $data
     * @return array
     */
    public static function generateTree(array $data)
    {
        $items  =   $tree   =   [];
        foreach ($data as $v) {
            $items[$v['id']] = $v;
        }

        foreach ($items as $k => $item) {
            if (isset($items[$item['parent_id']])) {
                $items[$item['parent_id']]['son'][] = &$items[$k];
            } else {
                $tree[] = &$items[$k];
            }
        }

        return $tree;
    }

    /**
     * 获取指定分类下的所有子分类
     * @param int $cat_id
     * @return int[]
     */
    public static function getSubCat(int $cat_id)
    {
        $all_cat    =   self::query()->active()->select(['id', 'parent_id'])->get();
        $sub_cat    =   [$cat_id];
        if ($all_cat->isEmpty()) {
            return $sub_cat;
        }

        $total_cat  =   [];

        foreach ($all_cat->toArray() as $item) {
            $total_cat[$item['id']]  =   $item;
        }

        foreach ($total_cat as $item) {
            if (in_array($item['parent_id'], $sub_cat)) {
                $sub_cat[]  =   $item['id'];
            }

            if (isset($total_cat[$item['parent_id']]) && in_array($total_cat[$item['parent_id']]['parent_id'], $sub_cat)) {
                $sub_cat[]  =   $item['id'];
            }
        }
        return array_unique($sub_cat);
    }

}
